package com.ruix.app.ui.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;

import com.hyphenate.easeui.EaseUI;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.constant.RuiXConstant;
import com.ruix.app.manager.UserManager;
import com.ruix.app.network.exception.NetworkUnusableException;
import com.ruix.app.network.exception.PermissionException;
import com.ruix.app.network.exception.RequestApiException;
import com.ruix.app.network.exception.TokenExpiredException;
import com.ruix.app.ui.main.MainActivity;
import com.ruix.app.ui.user.LoginActivity;
import com.ruix.app.util.ToastUtil;
import com.ruix.app.widget.CommonTitleBar;
import com.ruix.app.widget.DynamicLoadingView;
import com.umeng.analytics.MobclickAgent;

import android.support.v7.app.AppCompatActivity;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

/**
 * Created by hadexs on 2017/4/10.
 */

public abstract class BaseActivity extends AppCompatActivity {


    protected boolean canShowDailog = false;
    private DynamicLoadingView loadingView;
    private CommonTitleBar titleBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        beforeOnCreate();
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        init();// 初始化
    }

    private void init() {
        registerReceivers();
        initContentView();// 初始化布局文件
        initTitleBar();// 初始化标题栏
        initView(); // 初始化控件
        initListener();// 设置监听器
        initPresenter(); // 初始化presenter
        initLocalData();// 初始化数据
//        initTitleBarStatus();// 4.4及以上实现透明导航栏和状态栏
        //todo
//        EaseUI.getInstance().pushActivity(this);
    }

    protected  void beforeOnCreate(){

    }

    // 初始化布局文件及相关
    private void initContentView() {
        if (isUseBaseTitleBar()) {
            setContentView(R.layout.activity_base);
            RelativeLayout contentContainer = (RelativeLayout) findViewById(R.id.rl_gee_content_container);
            if (loadViewLayout() != 0) {
                LayoutInflater.from(this).inflate(loadViewLayout(), contentContainer);
            }
        } else {
            setContentView(loadViewLayout());
        }
    }

    // 初始化标题栏
    protected void initTitleBar() {
        if (!isUseBaseTitleBar()) {// 是否使用基础类提供的标题栏
            return;
        }
        titleBar = (CommonTitleBar) findViewById(R.id.nav);
        if (titleBar != null) {
//            titleBar.setOnClickLeftListener(this);
//            titleBar.setOnClickRightListener(this);
        }
    }

    public CommonTitleBar getTitleBar() {
        return titleBar;
    }

    // 是否使用基础类提供的标题栏
    protected boolean isUseBaseTitleBar() {
        return true;
    }

    // 加载布局文件
    protected abstract int loadViewLayout();

    // 初始化控件
    protected abstract void initView();

    // 初始化数据
    protected abstract void initLocalData();

    // 设置监听器
    protected abstract void initListener();

    // 初始化presenter
    protected void initPresenter() {
    }

    // 是否使用系统Bar
    protected boolean isUseNavigaBar() {
        return false;
    }

    // 是否用透明状态栏
    protected boolean isUseTransStatusBar() {
        return true;
    }


    // 4.4及以上实现透明导航栏和状态栏
    protected void initTitleBarStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isUseTransStatusBar()) {
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            tintManager.setStatusBarTintEnabled(true);
            // set a custom tint color for all system bars
//            tintManager.setTintColor(Color.parseColor("#FF99000FF"));
// set a custom navigation bar resource
//            tintManager.setNavigationBarTintResource(R.drawable.my_tint);
// set a custom status bar drawable
//            tintManager.setStatusBarTintDrawable(MyDrawable);
//            tintManager.setNavigationBarTintEnabled(true);
////            setTranslucentStatus(tr
        }
    }


    private static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = res.getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }

    protected boolean isStatusBarTintEnabled() {
        return true;
    }

    // 设置状态栏颜色
    protected int statusBarTintColor() {
        return R.color.colorPrimary;
    }

    protected boolean isFitsSystemWindows() {
        return true;
    }


    // 获取根布局
    public ViewGroup getRootView() {
        return (ViewGroup) ((ViewGroup) findViewById(Window.ID_ANDROID_CONTENT)).getChildAt(0);
    }

//    public void

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        canShowDailog = false;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        canShowDailog = true;
//        initBaseProperty();// 初始化预先加载数据
    }

    @Override
    protected void onPause() {
        super.onPause();
        canShowDailog = false;
//        if (presenter != null) {
//            presenter.onPause();
//        }
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        canShowDailog = true;
//        if (presenter != null) {
//            presenter.onResume();
//        }
//        MobclickAgent.onPageStart(((Object) this).getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void showSuccessTip(String msg) {
        if (canShowDailog) {
            ToastUtil.showNewMsg(msg);
        }
    }

    public void showSuccessTip(int msgResId) {
        if (canShowDailog) {
            ToastUtil.showNewSuccessMsg(msgResId);
        }
    }

    public void showErrorTip(String msg) {
        if (canShowDailog) {
            ToastUtil.showNewMsg(msg);
        }
    }

    public void showErrorTip(int msgResId) {
        if (canShowDailog) {
            ToastUtil.showNewErrorMsg(msgResId);
        }
    }

    public void showLoading() {
        showLoading(false);
    }

    public void showLoading(boolean bellow) {
        if (this.isFinishing() || !canShowDailog) {
            return;
        }
        synchronized (BaseActivity.this) {
            if (loadingView == null) {
                loadingView = DynamicLoadingView.newInstance();
                loadingView.showLoading(BaseActivity.this, bellow);
            }
        }
    }

    public void dismissLoading() {
        if (this.isFinishing()) {
            return;
        }

        synchronized (BaseActivity.this) {
            if (loadingView != null) {
                try {
                    loadingView.removeLoading();
                    loadingView = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setTitle(String title) {
        if (titleBar != null && title != null) {
            titleBar.setTitle(title);
        }
    }

    public void setTitle(int titleResId) {
        if (titleBar != null && titleResId != 0) {
            titleBar.setTitle(titleResId);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceivers();
//        EaseUI.getInstance().popActivity(this);
    }
    private void registerReceivers(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(RuiXConstant.NOTICE_LOGOUT);
        filter.addAction(RuiXConstant.NOTICE_PERMISSION_EXCEPTION);
        registerReceiver(baseReceiver, filter);
    }

    private void unregisterReceivers(){
        if (baseReceiver != null){
            unregisterReceiver(baseReceiver);
            baseReceiver = null;
        }
    }

    private BroadcastReceiver baseReceiver = new BroadcastReceiver(){

        @Override
        public void onReceive(Context context, Intent intent) {
            if (RuiXConstant.NOTICE_LOGOUT.equals(intent.getAction())){
                redirectLogin();
            } else if (RuiXConstant.NOTICE_PERMISSION_EXCEPTION.equals(intent.getAction())){
                permissionException();
            }
        }

    };

    private void redirectLogin(){
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        this.finish();
    }

    private void permissionException(){
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }


    public void resolveException(Throwable e){
        if (e instanceof SocketTimeoutException) {//SocketTimeoutException
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof UnknownHostException) { //解析不到域名 网络不通
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof NetworkUnusableException) { // 网络不可用，比如WiFi断开
            showErrorTip("网络在开小差，检查后再试吧");
        } else if (e instanceof IOException) { //socket 超时 网络超时 SocketTimeoutException
            showErrorTip("网络在开小差，检查后再试吧");
            e.printStackTrace();
        } else if (e instanceof TokenExpiredException){ //重新登录
            Intent intent = new Intent();
            intent.setAction(RuiXConstant.NOTICE_LOGOUT);
            RuiApplication.getAppContext().sendOrderedBroadcast(intent, null);
        } else if (e instanceof PermissionException){ //权限异常
            Intent intent = new Intent();
            intent.setAction(RuiXConstant.NOTICE_PERMISSION_EXCEPTION);
            RuiApplication.getAppContext().sendOrderedBroadcast(intent, null);
        }else if (e instanceof RequestApiException) {
            showErrorTip(e.getMessage());//
        } else {
//            showErrorTip(e.getMessage());
        }
    }


}
